# coding:utf-8

import urllib2
from bs4 import BeautifulSoup
# 使用流程：
# 1. 使用相关的 Handler处理器 来创建特定功能的处理器对象；
# 2. 然后通过 urllib2.build_opener()方法使用这些处理器对象，创建自定义opener对象；
# 3. 使用自定义的opener对象，调用open()方法发送请求。

class UseHandler:
    def basic(self):
        # 增加 debuglevel=1参数，还会将 Debug Log 打开
        handler = urllib2.HTTPHandler(debuglevel=1)
        opener = urllib2.build_opener(handler)
        request = urllib2.Request('http://www.baidu.com')
        response = opener.open(request)
        return response.read()

    def ipAgent(self):
        proxy1 = urllib2.ProxyHandler({'http':'182.119.204.214:8118'})
        proxy2 = urllib2.ProxyHandler({'http':'114.231.116.251:808'})
        opener = urllib2.build_opener(proxy1)
        request = urllib2.Request('http://www.baidu.com')
        response = opener.open(request)
        return response.read()

    def ipAgentEnhance(self):
        proxy_list = [
            {'http': '182.119.204.214:8118'},
            {'http': '114.231.116.251:808'},
            {'http': '115.209.28.178:8118'},
            {"http": '110.73.33.210:8123'}
        ]
        import random
        proxy2 = urllib2.ProxyHandler(random.choice(proxy_list))
        opener = urllib2.build_opener(proxy2)
        request = urllib2.Request('http://www.baidu.com')
        response = opener.open(request)
        return response.read()



if __name__ == '__main__':
    u = UseHandler()
    # html = u.basic()
    # print(BeautifulSoup(html,'html.parser').get_text())

    # html = u.ipAgent()
    # print(BeautifulSoup(html,'html.parser').get_text())

    html = u.ipAgentEnhance()
    print(BeautifulSoup(html,'html.parser').get_text())
